import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseGuards, Req, Res, Session } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PaginationQueryDto } from '../common/dto/pagination-query.dto';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Response, Request } from 'express';
import { User } from './entities/user.entity';
import { RoleGuard } from '../auth/role-auth.guard';
import { roleConstants } from '../auth/constants';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto, @Session() session: Record<string, any>) {
    return this.usersService.register(createUserDto, session);
  }

  @UseGuards(JwtAuthGuard, RoleGuard)
  @Get()
  findAll(@Query() paginationQuery: PaginationQueryDto) {
    return this.usersService.findAll(paginationQuery);
  }

  @UseGuards(JwtAuthGuard, RoleGuard)
  @Get('/info')
  findOne(@Req() request: Request, @Query('id') id: number) {
    if ((request.user as User).role === roleConstants.admin) return this.usersService.findOne(id);
    const user = request.user as User;
    return this.usersService.findOne(user.id);
  }

  @UseGuards(JwtAuthGuard)
  @Patch(':id')
  update(@Req() request: Request, @Body() updateUserDto: UpdateUserDto) {
    const user = request.user as User;
    return this.usersService.update(user.id, updateUserDto);
  }

  @UseGuards(JwtAuthGuard, RoleGuard)
  @Delete(':id')
  remove(@Param('id') id: number) {
    return this.usersService.remove(id);
  }

  @Post('login')
  login(@Body() loginUserDto: LoginUserDto) {
    return this.usersService.login(loginUserDto);
  }

  @Get('/captcha')
  createCAPTCHA(@Res() res: Response, @Session() session: Record<string, any>) {
    return this.usersService.createCAPTCHA(res, session);
  }
}
